package com.abe.config;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;

import com.abe.strengthtrainer.R;
import com.abe.utils.ConvertUtils;
import com.abe.utils.NormalUtils;

/** 读卡器串口相关 */
@SuppressLint("SimpleDateFormat")
public class CardReaderUtils {

	/**************************** 读卡器命令集合 ******************************/
	public static byte[] READ_CARD_NUM_BEEP = new byte[] { (byte) 0x01,
			(byte) 0x08, (byte) 0xa1, (byte) 0x20, (byte) 0x00, (byte) 0x00,
			(byte) 0x01, (byte) 0x77 };
	public static byte[] READ_CARD_NUM_NO_BEEP = new byte[] { (byte) 0x01,
			(byte) 0x08, (byte) 0xa1, (byte) 0x20, (byte) 0x00, (byte) 0x00,
			(byte) 0x00, (byte) 0x77 };

	/**************************** 读卡器命令集合 ******************************/

	public static byte OK = 0x00;
	public static byte ERR = 0x01;

	/** 数据解析 */
	public static CardReadBean Parser(byte[] RevDataBuffer) {
		CardReadBean bean = new CardReadBean();

		/** 标识信息：成功或错误编号 */
		byte Flag;
		/** 命令 */
		byte cmd;
		byte pkttype;
		byte pktlength = 0x0;
		boolean status = CardReaderUtils.CheckSumOut(RevDataBuffer,
				RevDataBuffer[1]);
		/** 原始数据 */
		String ss = ConvertUtils.bytes2HexString(RevDataBuffer,
				RevDataBuffer[1]);
		/** 解析标识 */
		int flag = 0;
		String text = new SimpleDateFormat("yyyy-MM-dd HH:mm")
				.format(new Date()) + ":" + "接收数据：" + ss + "\n";
		System.out.println("串口接收数据：/n" + text);
		if (status == true) {
			pkttype = RevDataBuffer[0];
			pktlength = RevDataBuffer[1];
			cmd = RevDataBuffer[2];
			Flag = RevDataBuffer[4];
			for (int i = 0; i < pktlength - 6; i++) {
				RevDataBuffer[i] = RevDataBuffer[i + 5];
			}

			if (pkttype == 0x01 && cmd == (byte) 0xa1) {
				if (Flag == OK) {
					flag = 1;
					/** 卡号 */
					ss = ConvertUtils.bytes2HexString(RevDataBuffer, 6);
				} else {
					flag = -1;
					/** 读卡号失败 */
					ss = NormalUtils.getString(R.string.card_read_error);
				}
			}
		}
		bean.setFlag(flag);
		bean.setInfo(ss);
		return bean;
	}

	public static void CheckSum(byte[] buf, byte len) {
		byte i;
		byte checksum;
		checksum = 0;
		for (i = 0; i < (len - 1); i++) {
			checksum ^= buf[i];
		}
		buf[len - 1] = (byte) ~checksum;
	}

	public static boolean CheckSumOut(byte[] buf, byte len) {
		byte i;
		byte checksum;
		checksum = 0;
		for (i = 0; i < (len - 1); i++) {
			checksum ^= buf[i];
		}
		if (buf[len - 1] == (byte) ~checksum) {
			return true;
		}
		return false;
	}

	public static class CardReadBean {
		/** 0:数据解析失败，-1：读失败，1：读成功 */
		private int flag;
		private String info;

		public int getFlag() {
			return flag;
		}

		public void setFlag(int flag) {
			this.flag = flag;
		}

		public String getInfo() {
			return info;
		}

		public void setInfo(String info) {
			this.info = info;
		}

		public CardReadBean() {
		}

		public CardReadBean(int flag, String info) {
			this.flag = flag;
			this.info = info;
		}

	}

}